/*
tms   切片特性
1.tms切片是正方形切片。
2.即每一行的瓦片数量等于每一列的瓦片数量每一行的瓦片数量   n = Math.pow(2,level);
3.切面原点在左下方，左下方最小，右上方最大
4.即以左下点为起始点，以此向右，向上得到其余的瓦片号，经纬度
 */

namespace('n2.tms');

n2.tms=function(){
    this._viwer = null;
    this._camera = null;
    this._handler = null;
    this._scene = null;
    n2.base(this, n2.main);
};

n2.definePrototype(n2.tms.prototype, {
    viewer: {
        get: function () {
            return this._viewer;
        },
        set: function (value) {
            this._viewer = value;
        }
    },
    handler: {
        get: function () {
            return this._handler;
        },
        set: function (value) {
            this._handler = value;
        }
    },
    camera: {
        get: function () {
            return this._camera;
        },
        set: function (value) {
            this._camera = value;
        }
    },
    scene:{
    	get: function () {
            return this._scene;
        },
        set: function (value) {
            this._scene = value;
        }
    }
});

n2.tms.prototype.init = function(rect){
	
	var self =this;
	var viewer = n2.viewer;
	//self.entities = null;      //全球瓦片
    self.entities =  viewer.entities;
	var tile = "";
	var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
	
    var camera = viewer.camera;
	
    var rectangleSc = null ;    //视角范围

    var recDefiu = new Cesium.Rectangle(      //全球     
                Cesium.Math.toRadians(-180),
                Cesium.Math.toRadians(-90),
                Cesium.Math.toRadians(180),
                Cesium.Math.toRadians(90));

    var rectangle = rect? rect:recDefiu;

	self.bottomP();   //初始化底图
	

    var rectangle2 = new Cesium.Rectangle(      //湖北范围     
                Cesium.Math.toRadians(108.0),
                Cesium.Math.toRadians(29.0),
                Cesium.Math.toRadians(116.0),
                Cesium.Math.toRadians(33.0));


    //目标区域
    var recminX = rectangle.west*180/Math.PI;
    var recmaxX = rectangle.east*180/Math.PI;
    var recmaxY = rectangle.north*180/Math.PI;
    var recminY = rectangle.south*180/Math.PI;

    var nowLevel = 0;
	 
  	
	//鼠标滚动变化层级------
	//双手指放大缩小事件
    handler.setInputAction(function (event){ 
    	
    	//南海诸岛的提示地图出现和小时
    	var ig = document.querySelector('#map');
    	//获取当前视角的高度                                        
        var height1 = camera.position;
        var height2 = Cesium.Cartographic.fromCartesian(height1).height;
        
        
        if(height2<=1509775){
        	
        	ig.style.display = 'block';
        	
        }else{
        	
        	ig.style.display = 'none';
        }

		var level = self.showLevel(viewer.scene);    //根据相机的高度来确定层级

        if(level>3){

            return '';
        }

        rectangleSc = camera.computeViewRectangle();   //视角下的矩形

        //弧度-----度---------视角
        //minx    西
        var w = rectangleSc.west*180/Math.PI;   
        //maxX    东
        var e = rectangleSc.east*180/Math.PI;
        //miny   南
        var s = rectangleSc.south*180/Math.PI;
        //maxy    北
        var n = rectangleSc.north*180/Math.PI;
       
        //如果变换层级，那么就需要更换瓦片
        if(level!== nowLevel){
        	
        	console.log(level)

            nowLevel = level;
                        
            //加载瓦片号的区域包含视角，即视角在瓦片区域移动，则只加载视角内的
           if(w>=recminX && e<=recmaxX && s>=recminY && n<=recmaxY) {
               
                var nowTile = self.bBox(w,s,e,n,nowLevel);

            }else{

                //当视角包含所需加载瓦片的地方，该地区当前所有的瓦片，这样的情况一般层级小，瓦片也少

                var nowTile = self.bBox(recminX,recminY,recmaxX,recmaxY,nowLevel);

            }


            if (self.entities != null){

                self.entities.removeAll();
             }

            

            var tileLen = nowTile.length;

            //为所有需要加载的瓦片号发送请求，得到瓦片号base64编码
            for(var i=0;i<tileLen;i++){
            	
                var tilArry = nowTile[i].toString();
//              console.log(tilArry)
                n2.ajax.get('http://' +n2.webGisLocalhost+":"+n2.webGisProt+'/api/EQ_geoJsonTile',{tile_code:tilArry}).then(function(res){

                    var res = JSON.parse(res);

                    var imgBase = 'data:image/jpge;base64,'+res.imgBase64;

                    var l = res.level;
                    var cl = res.cloumn;
                    var row = res.row;

                    var posi = self.cart(l,cl,row);

                    self.entities.add({
                        rectangle: {
                            coordinates: posi,   //图片被包围的矩形
                            material: imgBase,    //图片base64编码
                            height:0
                        }
                    })               
                })

            }             
        }else{
        	return false;
        }
	},Cesium.ScreenSpaceEventType.PINCH_MOVE);
//},Cesium.ScreenSpaceEventType.WHEEL)


    //移动视角也要实时更新当前屏幕视角的瓦片
    
//  handler.setInputAction(function (){
//
//      var nowRecLook = camera.computeViewRectangle();  //当前视角
//
//      var nowRecLookW = nowRecLook.west*180/Math.PI;
//
//      var nowRecLookE = nowRecLook.east*180/Math.PI;
//
//      var nowRecLookS = nowRecLook.south*180/Math.PI;
//
//      var nowRecLookN = nowRecLook.north*180/Math.PI;
//
//      if(nowRecLookW>=recminX && nowRecLookE<=recmaxX && nowRecLookS>=recminY && nowRecLookN<=recmaxY) {      
//
//          //当前视角包含加载区域
//             
//              return '';
//
//      }
//
//      if (rectangleSc === nowRecLook) { 
//
//         //视角无变化    
//            
//          return '';
//
//      }else{
//
//          rectangleSc = nowRecLook;
//
//          //弧度-----度---------视角
//          //minx    西
//          var w = rectangleSc.west*180/Math.PI;   
//          //maxX    东
//          var e = rectangleSc.east*180/Math.PI;
//          //miny   南
//          var s = rectangleSc.south*180/Math.PI;
//          //maxy    北
//          var n = rectangleSc.north*180/Math.PI;
//
//
//          var nowTile = self.bBox(w,s,e,n,nowLevel);
//
//          if (self.entities != null){
//
//              self.entities.removeAll();
//           }
//
//          self.entities =  viewer.entities;
//
//          var tileLen = nowTile.length;
//
//          //为所有需要加载的瓦片号发送请求，得到瓦片号base64编码
//          for(var i=0;i<tileLen;i++){
//              var tilArry = nowTile[i].toString();
//              n2.ajax.get('http://59.173.238.36:10040/api/EQ_geoJson',{tile_code:tilArry}).then(function(res){
//
//                  var res = JSON.parse(res);
//
//                  var imgBase = 'data:image/jpge;base64,'+res.imgBase64;
//
//                  var l = res.level;
//                  var cl = res.cloumn;
//                  var row = res.row;
//
//                  var posi = self.cart(l,cl,row);
//
//                  self.entities.add({
//                      rectangle: {
//                          coordinates: posi,   //图片被包围的矩形
//                          material: imgBase    //图片base64编码
//                      }
//                  })               
//              })
//
//          } 
//      }
//
// },Cesium.ScreenSpaceEventType.MOUSE_MOVE) 
}



n2.tms.prototype.bottomP = function(){
	
	var self = this;
	
	var priTile = self.bBox(-180,-90,180,90,1);
	
	for(var i=0;i<priTile.length;i++){
            	
        var tilArry = priTile[i].toString();
                console.log(tilArry)
        n2.ajax.get(n2.webGisLocalhost + ':' + n2.webGisProt + '/api/EQ_geoJsonTile',{tile_code:tilArry}).then(function(res){

            var res = JSON.parse(res);

            var imgBase = 'data:image/jpge;base64,'+res.imgBase64;

            var l = res.level;
            var cl = res.cloumn;
            var row = res.row;

            var posi = self.cart(l,cl,row);

            self.entities.add({
                rectangle: {
                    coordinates: posi,   //图片被包围的矩形
                    material: imgBase,    //图片base64编码
                    height:0
                }
            })               
        })

    }             

}
//},Cesium.ScreenSpaceEventType.WHEEL)




	

//高度获取层级
n2.tms.prototype.showLevel = function(scene){

	var height = Math.ceil(scene.camera.positionCartographic.height);

    if (height > 22703492) {
        return 1;
    }

    if ((height <= 22703492) && (height > 11235821)) {
        return 2;
    }

    if (height <= 11235821 && height > 6117472) {
        return 3;
    }

    if (height <= 6117472 && height > 2986202) {
        return 4;
    }

    if (height <= 2986202 && height > 1457025) {
        return 5;
    }

    if (height <= 1457025 && height > 710778) {
        return 6;
    }

    if (height <= 710778 && height > 346653) {
        return 7;
    }

    if (height <= 346653 && height > 157332) {
        return 8;
    }
    if (height <= 157332 && height > 88644) {
        return 9;
    }
    if (height <= 88644 && height > 43246) {
        return 10;
    }

    if (height <= 43246 && height > 21099) {
        return 11;
    }

    if (height <= 21099 && height > 11888) {
        return 12;
    }

    if (height <= 11888 && height > 5802) {
        return 13;
    }

    if (height <= 5802 && height > 2832) {
        return 14;
    }

    if (height <= 2832 && height > 1383) {
        return 15;
    }

    if (height <= 1383 && height > 585) {
        return 16;
    }

    if (height <= 585 && height > 281) {
        return 17;
    }

    if (height <= 281 && height > 159) {
        return 18;
    }

    if (height <= 159 && height > 78) {
        return 19;
    }

    if (height <= 78 && height > 39) {
        return 20;
    }

    if (height <= 39 && height > 19) {
        return 21;
    }

    if (height <= 19) {
        return 22;
    }
}




//根据特定请求范围和当前层级找出范围内的瓦片号,二维数组存起来
n2.tms.prototype.bBox = function (minX,minY,maxX,maxY,level) {
    //最小瓦片编号
    var CMin = Math.floor([(minX+180)/180]*Math.pow(2,level));
    var RMin = Math.floor([(minY+90)/180]*Math.pow(2,level));

    //最大瓦片编号
    var CMax = Math.floor([(maxX+180)/180]*Math.pow(2,level));
    var RMax = Math.floor([(maxY+90)/180]*Math.pow(2,level));

    //命中的瓦片行数为
    var CCount = (CMax-CMin+1);

    //命中的瓦片行数为
    var RCount = (RMax-RMin+1);

    //命中的瓦片数目为    
    var CRnumber = CCount*RCount;

    //屏幕左下角的瓦片编号
    var leftCR = [CMin,RMin];

    //屏幕右上角的瓦片编号
    var rightCR = [CMax,RMax];

    var tileArry = [];   //瓦片号二维数组

    for(var i=0;i<CCount;i++){
        for(var j=0;j<RCount;j++){
            tileArry.push([level,CMin+i,RMin+j]);
        }
    }

    return tileArry;
}



//瓦片号获取经纬度
n2.tms.prototype.cart = function (level,column,row){
    //瓦片左下角经纬度
    var leftX = column*180/Math.pow(2,level)-180;
    var leftY = row*180/Math.pow(2,level)-90;

    //瓦片右上角
    var rightX = (column+1)*180/Math.pow(2,level)-180;
    var rightY = (row+1)*180/Math.pow(2,level)-90;

    //我们需要知道是中心点的坐标
    var longi = (rightX+leftX)/2;
    var lati = (rightY+leftY)/2;

    return Cesium.Rectangle.fromDegrees( leftX, leftY, rightX, rightY);
}


